package com.example.lib_login.code

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.transition.TransitionInflater
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.view.ViewCompat
import androidx.core.widget.addTextChangedListener
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import com.example.lib_login.LoginViewModel
import com.example.lib_login.MainActivity
import com.example.lib_login.R
import com.example.lib_login.dataBinding.Events
import com.example.lib_login.databinding.AlertWindowViewBinding
import com.example.lib_login.databinding.FragmentVerificationCodeBinding
import com.example.lib_login.phone.PhoneFragment
import com.example.lib_login.pwd.PasswordFragment
import com.example.lib_ui_base.WjbAlertView
import java.sql.Time
import java.util.Timer
import java.util.TimerTask

//验证码
class VerificationCodeFragment : Fragment() {
    private val viewModel:LoginViewModel by activityViewModels()
    private lateinit var binding:FragmentVerificationCodeBinding
    private val event = Events()

    var time = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        sharedElementEnterTransition = TransitionInflater.from(context).inflateTransition(android.R.transition.move)
    }


    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentVerificationCodeBinding.inflate(inflater,container,false)
        return binding.root
    }



    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)



        time = viewModel.MY_TIME
        binding.viewModel = viewModel
        binding.events = event
        //发送验证码
        //TODO 测试用的
        sendCode()

        //验证是否正确
        verificationCode()


        binding.go.setOnClickListener {
            requireActivity().supportFragmentManager.beginTransaction().apply {
                replace(R.id.fragmentContainerView, PhoneFragment())
                viewModel.timer.cancel()
                commit()
            }
        }

        binding.textView10.setOnClickListener{
            requireActivity().supportFragmentManager.beginTransaction().apply {
                replace(R.id.fragmentContainerView, PasswordFragment())
                viewModel.timer.cancel()
                addToBackStack(null)
                commit()
            }
        }


    }

    override fun onStart() {
        super.onStart()
        //启动定时器
        viewModel.timer.cancel()
        viewModel.timer = Timer()
        startTime()
    }


    //验证
    private fun verificationCode(){
        binding.editTextNumberPassword2.addTextChangedListener(
            onTextChanged = {text, start, before, count ->
                if(text?.length == 6){
                    viewModel.userManager.registrationOrLogin(viewModel.phoneNumber.get()!!,text.toString(),
                        onEnd = {
                            if (it) {
                                requireActivity().startActivity(Intent(activity, MainActivity::class.java))
                                requireActivity().finish()
                            } else {
                                val mBinding = AlertWindowViewBinding.inflate(LayoutInflater.from(requireContext()))
                                mBinding.textView2.text = "验证码错误"
                                WjbAlertView(requireContext(),mBinding.root).show()
                            }
                        }
                    )
                }
            }
        )
    }

    //发送
    private fun sendCode(){
        viewModel.userManager.requestSMSCode(viewModel.phoneNumber.get()!!,
            onEnd = {
                if (it) {
                    val mBinding = AlertWindowViewBinding.inflate(LayoutInflater.from(requireContext()))
                    mBinding.root.setBackgroundResource(R.drawable.success_alert_view)
                    mBinding.imageView.visibility = View.INVISIBLE
                    mBinding.textView2.setTextColor(Color.BLACK)
                    mBinding.textView2.text = "发送成功"
                    WjbAlertView(requireContext(),mBinding.root).show()
                } else {
                    val mBinding = AlertWindowViewBinding.inflate(LayoutInflater.from(requireContext()))
                    mBinding.textView2.text = "发送失败"
                    WjbAlertView(requireContext(),mBinding.root).show()
                }
            }
        )
    }

    private fun startTime(){
        //发送验证码，开启定时器
        viewModel.timer.schedule(object :TimerTask(){
            override fun run() {
                time--
                if(time == 0){
                    viewModel.timer.cancel()
                    viewModel.time.set("重新获取")
                    time = viewModel.MY_TIME
                }else {
                    viewModel.time.set("$time")
                }
            }
        },0,1000)
    }

}